<template>
  <div>
 <com-head title="商品详情页"/>
    <div class="wrap">
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item v-for="banner in pics" :key="banner.id">
          <img :src="banner.pic" alt="">
        </van-swipe-item>
      </van-swipe>
      <h3>
      {{basicInfo.name}}
      </h3>
      <div class="content" v-html="content"></div>
    </div>

    <!-- 商品导航 -->
<van-goods-action>
  <van-goods-action-icon to='/home' icon="wap-home-o" text="首页" />
  <van-goods-action-icon to='/cart' :badge="$store.state.cart.items.length||''" icon="cart-o" text="购物车" />
  <van-goods-action-button @click="showSku(0)" type="warning" text="加入购物车" />
  <van-goods-action-button  @click="showSku(1)" type="danger" text="立即购买" />
</van-goods-action>
    <!-- 弹出层 -->
<van-popup
    v-model="show"
    position="bottom"
    round
    closeable
    :style="{ height: '35%' }"
    >

  <van-card
    :num="sku.number"
    :price="sku.minPrice"
    :title="sku.name"
    :thumb="sku.pic"
  >
  <template #footer>
 <van-stepper v-model="sku.number" />
 <van-button round  size="large" type="danger" @click="commintItem">确认</van-button>
  </template>
</van-card>
</van-popup>
  </div>
</template>

<script>
import ComHead from '@components/ComHead'
import { fetchDetail, addCart } from '@api'
import { Toast } from 'vant'
export default {
  data () {
    return {
      basicInfo: [], // 基础信息
      content: '', // 详情富文本
      pics: [], // 轮播图
      sku: {
        number: 1
      },
      show: false,
      actionType: 0 // 0加入购物车 1立即购买
    }
  },
  created () {
    this.fetchDetail()
  },
  methods: {
    commintItem () {
      if (this.actionType === 0) {
        addCart({
          goodsId: this.sku.id,
          number: this.sku.number,
          token: localStorage.getItem('token')
        }).then(res => {
          if (res.data.code === 0) {
            this.$store.commit('cart/init_cart_info', {
              items: res.data.data.items,
              total: res.data.data.price
            })
            Toast({
              type: 'success',
              message: '加入购物车成功'
            })
          } else {
            alert('加入购物车')
          }
        })
        this.show = false
      }
    },
    showSku (type) {
      this.show = true
      this.actionType = type
    },
    fetchDetail () {
      fetchDetail(
        this.$route.params.id
      ).then(res => {
        if (res.data.code === 0) {
          this.basicInfo = res.data.data.basicInfo
          this.pics = res.data.data.pics
          this.content = res.data.data.content.replace(/<img/gi, '<img style="display:block;width:100%"')
          this.sku = { ...this.sku, ...res.data.data.basicInfo }
        }
      })
    }
  },
  components: {
    ComHead
  }
}
</script>

<style lang="scss" scoped>
.wrap{
  padding-top: 46px;
  padding-bottom: 40px;
  .my-swipe{
    img{
      width: 100%;
    }
  }
}

</style>
